import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/Login/LoginView.vue')
  },
  {
    path: '/register',
    name: 'register',
    component: () => import('../views/Login/RegisterView.vue')
  },
  {
    path: '/home',
    name: 'home',
    component: () => import('../views/User/Home/HomeView.vue')
  },
  {
    path: '/house',
    name: 'house',
    component: () => import('../views/User/HouseInformation/HouseView.vue')
  },
  {
    path: '/message',
    name: 'message',
    component: () => import('../views/User/HouseInformation/MessageView.vue')
  },
  {
    path: '/center',
    name: 'center',
    component: () => import('../views/User/Center/PersonCenterView.vue')
  },
  {
    path: '/adminHome',
    name: 'adminHome',
    component: () => import('../views/Admin/Home/HomeView.vue')
  },
  {
    path: '/userAccount',
    name: 'userAccount',
    component: () => import('../views/Admin/UserInformation/userAccountView.vue')
  },
  {
    path: '/houseInfo',
    name: 'houseInfo',
    component: () => import('../views/Admin/House/HouseView.vue')
  },
  {
    path: '/userAppointment',
    name: 'userAppointment',
    component: () => import('../views/Admin/UserInformation/userAppointmentView.vue')
  },
  {
    path: '/userMess',
    name: 'userMess',
    component: () => import('../views/Admin/UserInformation/userMessView.vue')
  }
]

// 设置mode为history
const router = new VueRouter({
  mode: 'history', // 使用HTML5 history模式
  routes
})

router.beforeEach((to, from, next) => {
  // 如果访问的是登录页面（无需权限），直接放行
  if (to.path === '/login' || to.path === '/register') return next()

  const userToken = sessionStorage.getItem('token')
  const adminToken = sessionStorage.getItem('adminToken')

  if (
    to.path === '/adminHome' ||
    to.path === '/userAccount' ||
    to.path === '/houseInfo' ||
    to.path === '/userAppointment' ||
    to.path === '/userMess'
  ) {
    if (adminToken) {
      return next()
    } else {
      alert('请先登录')
      return next('/login')
    }
  } else {
    if (userToken) {
      return next()
    } else {
      alert('请先登录')
      return next('/login')
    }
  }
})

export default router